library(optparse)
library(tidyverse)
library(magrittr)
library(extrafont)

configGet <- function(configData, key) {
  configData %>%
    filter(arg == key) %>%
    .$value
}

option_list <- list(
  make_option("--samplespath", default = "samples.csv", type = "character", help = "Sample data path"),
  make_option("--speciespath", default = "species.csv", type = "character", help = "Data of species path"),
  make_option("--envipath", default = "envi.csv", type = "character", help = "Environmental data path"),
  make_option("--percentpath", default = "percent.csv", type = "character", help = "Percentage data path"),
  make_option("--grouppath", default = "group.txt", type = "character", help = "groupFile path"),
  make_option("--filepath", default = "./", type = "character", help = "package path of image output"),
  make_option("--xtext_style", default = "sans:bold.italic:16", type = "character", help = "X text style Font:font type:font size"),
  make_option("--ytext_style", default = "sans:bold.italic:16", type = "character", help = "Y text style Font:font type:font size"),
  make_option("--xlab_style", default = "sans:bold.italic:18", type = "character", help = "X lab style Font:font type:font size:name"),
  make_option("--ylab_style", default = "sans:bold.italic:18", type = "character", help = "Y lab style Font:font type:font size:name"),
  make_option("--main_style", default = "sans:bold.italic:12: ", type = "character", help = "Main style Font:font type:font size:name"),
  make_option("--resolution", default = "300", type = "numeric", help = "Set the resolution to allow 72,96,300 or 600"),
  make_option("--pc", default = "", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

fenge <- function(str) {
  return(strsplit(str, ":")[[1]])
}

cbiaoge <- function(biaoge) {
  rownames(biaoge) <- biaoge[, 1]
  biaoge <- biaoge[, -1]
  return(biaoge)
}

plotConfigData <- read_tsv(opt$pc, col_names = F, col_types = "cc") %>%
  set_colnames(c("arg", "value"))

x <- configGet(plotConfigData, "x")
y <- configGet(plotConfigData, "y")
ox <- configGet(plotConfigData, "ox") %>%
  as.numeric()
oy <- configGet(plotConfigData, "oy") %>%
  as.numeric()
pointSize <- configGet(plotConfigData, "pointSize")
showSample <- configGet(plotConfigData, "showSample") %>%
  as.logical()
showEnv <- configGet(plotConfigData, "showEnv") %>%
  as.logical()
showSpecies <- configGet(plotConfigData, "showSpecies") %>%
  as.logical()
speciesPointSize <- configGet(plotConfigData, "speciesPointSize")
width <- configGet(plotConfigData, "width") %>%
  as.numeric()
height <- configGet(plotConfigData, "height") %>%
  as.numeric()
envNameColor <- configGet(plotConfigData, "envNameColor")
envLineColor <- configGet(plotConfigData, "envLineColor")
speciesColor <- configGet(plotConfigData, "speciesColor")
sampleFont <- configGet(plotConfigData, "sampleFont")
envFont <- configGet(plotConfigData, "envFont")
speciesFont <- configGet(plotConfigData, "speciesFont")
xFont <- configGet(plotConfigData, "xFont")
xTitleFont <- configGet(plotConfigData, "xTitleFont")
yFont <- configGet(plotConfigData, "yFont")
yTitleFont <- configGet(plotConfigData, "yTitleFont")
mainTitle <- configGet(plotConfigData, "mainTitle") %>%
  as.character()
mainTitleFont <- configGet(plotConfigData, "mainTitleFont") %>%
  as.numeric()
legendFont <- configGet(plotConfigData, "legendFont")
legendTitle <- configGet(plotConfigData, "legendTitle")
legendTitleFont <- configGet(plotConfigData, "legendTitleFont")
fontFamily <- configGet(plotConfigData, "fontFamily")
baseFamily <- fontFamily
baseFamily

origin_point <- c(ox, oy)
xyread <- c(x, y)
main_style <- fenge(opt$main_style)
xtext_style <- fenge(opt$xtext_style)
ytext_style <- fenge(opt$ytext_style)
xlab_style <- fenge(opt$xlab_style)
ylab_style <- fenge(opt$ylab_style)
aa <- read.csv(opt$percentpath, check.names = FALSE)
RDA1 <- paste(aa[xyread[1], 1], ":", aa[xyread[1], 2])
RDA2 <- paste(aa[xyread[2], 1], ":", aa[xyread[2], 2])
bb <- read.csv(opt$samplespath, check.names = FALSE)
bb <- as.matrix(cbiaoge(bb))
cc <- read.csv(opt$speciespath, check.names = FALSE)
cc <- as.matrix(cbiaoge(cc))
dd <- read.csv(opt$envipath, check.names = FALSE)
dd <- as.matrix(cbiaoge(dd))
samples <- data.frame(sample = row.names(bb), RDA1 = bb[, 1], RDA2 = bb[, 2])
species <- data.frame(spece = row.names(cc), RDA1 = cc[, 1], RDA2 = cc[, 2])
envi <- data.frame(en = row.names(dd), RDA1 = dd[, 1], RDA2 = dd[, 2])
ll <- nrow(envi) * 2
line_x <- 1:ll
line_x[seq(1, ll, 2)] <- origin_point[1]; line_x[seq(2, ll, 2)] <- envi[, 2]
line_y <- 1:ll
line_y[seq(1, ll, 2)] <- origin_point[2]; line_y[seq(2, ll, 2)] <- envi[, 3]
groupnames <- as.character(t(matrix(rep(rownames(envi), 2), ncol = 2)))
line_g <- groupnames
line_data <- data.frame(x = line_x, y = line_y, group = line_g)
resolution <- opt$resolution; if (resolution != 72 &&
  resolution != 96 &&
  resolution != 300 &&
  resolution != 600) { resolution <- 300 }
if (opt$grouppath != "") {
  gd <- read.table(opt$grouppath, header = T)
  groupline <- rep(NA, nrow(samples))
  key1 <- as.character(samples[, 1])
  key2 <- as.character(gd[, 1])
  ll <- length(key1)
  linedata <- rep(NA, ll)
  for (i in 1:ll) {
    a <- key1[i]
    b <- which(key2 == a)[1]
    if (length(b) == 1) {
      linedata[i] <- as.character(gd[b, 2])
    }
  }
  line_data[which(is.na(linedata))] <- "no group"
  samples[, 4] <- linedata
}

suppressMessages(library("ggrepel"))
suppressMessages(library("ggplot2"))
p <- ggplot(data = samples, aes(RDA1, RDA2)) +
  theme_bw(base_family = baseFamily) +
  theme(panel.grid = element_blank()) +
  labs(x = RDA1, y = RDA2) +
  theme(axis.text.y = element_text(family = baseFamily, face = ytext_style[2], size = yFont),
        axis.text.x = element_text(family = baseFamily, face = xtext_style[2], size = xFont),
        axis.title.x = element_text(size = xTitleFont, family = baseFamily, face = xlab_style[2]),
        axis.title.y = element_text(size = yTitleFont, family = baseFamily, face = ylab_style[2]),
        title = element_text(size = as.numeric(mainTitleFont), family = baseFamily, face = main_style[2]),
        plot.title = element_text(hjust = 0.5, size = mainTitleFont), legend.text = element_text(size = legendFont),
        legend.title = element_text(size = legendTitleFont),
  )
if (showSpecies) {
  p <- p + geom_text_repel(data = species, aes(label = spece, x = RDA1, y = RDA2), color = as.character(speciesColor),
                           size = as.numeric(speciesFont), family = baseFamily)
}

if (!is.na(mainTitle)) {
  p <- p + ggtitle(mainTitle)
}

p <- p +
  geom_hline(yintercept = origin_point[2], linetype = 2) +
  geom_vline(xintercept = origin_point[1], linetype = 2)
if (showSpecies) {
  p <- p + geom_point(data = species, size = as.numeric(speciesPointSize), color = as.character(speciesColor), shape = 18)
}
if (showEnv) {
  p <- p + geom_text(data = envi, aes(label = en), color = as.character(envNameColor), size = as.numeric(envFont))
}
if (showEnv) {
  p <- p + geom_line(data = line_data, aes(x = x, y = y, group = group), color = envLineColor)
}

sampleColDf <- read_tsv("Class_Color.txt") %>%
  select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
  deframe()

if (opt$grouppath != "") {
  p <- p +
    theme(legend.position = c("right")) +
    labs(color = "group")
  p <- p + geom_point(aes(color = as.character(samples[, 4])), size = as.numeric(pointSize))
  if (showSample) {
    p <- p + geom_text_repel(aes(label = sample, color = as.character(samples[, 4])), show.legend = F,
                             size = as.numeric(sampleFont), family = baseFamily)
  }

  if (!is.na(legendTitle)) {
    p <- p +
      scale_colour_manual(legendTitle, values = sampleCols)
  }else {
    p <- p +
      scale_colour_manual("", values = sampleCols)
  }

  if (nrow(sampleColDf) == 1) {
    p <- p +
      theme(legend.position = 'none')
  }

}else {
  p <- p + theme(legend.position = "none", legend.title = element_blank())
  p <- p + geom_point(color = samples[, 4][1], size = as.numeric(pointSize))
  if (showSample) {
    p <- p + geom_text_repel(aes(label = sample), color = samples[, 4][1], size = as.numeric(sampleFont),
                             family = baseFamily)
  }
}

ggsave(paste0(opt$filepath, "/", "rdacca", ".pdf"), plot = p, width = width, height = height, dpi = resolution)



